app.controller('programController',['$scope','storageService',
    function ($scope, storageService) {
        $scope.days = storageService.getItem('days');
        angular.element(document).ready(function () {
            var activeOne = "thursday";
            var myScroller = new IScroll('#wrapper', {
                eventPassthrough: true,
                scrollX: true,
                scrollY: false,
                preventDefault: false,
                startX: smallestMarginLeft("thursday")
            });
            function smallestMarginLeft(divId){
                var elm = document.getElementById(divId);
                var elementArray = elm.getElementsByClassName('timeline-event');
                var smallestMargin = 2000;
                for(var i = 0; i < elementArray.length; i++){
                    if(parseInt(elementArray[i].style.marginLeft, 10) < smallestMargin){
                        smallestMargin = parseInt(elementArray[i].style.marginLeft, 10);
                    }
                }
                return smallestMargin * -1;
            };

            $scope.setActive = function(venueId){
                activeOne = venueId;
                myScroller.scrollTo(smallestMarginLeft(venueId), 0, 500, IScroll.utils.ease.elastic);
            };
            $scope.isActive = function(dayName){
                return activeOne === dayName;
            };
        });
        
        var paths = ['events', 'venues'];

        for(var i in paths){
            $scope[paths[i]] = storageService.getItem(paths[i]);

            // Check for updates and update data when done
            storageService.dataUpdated(paths[i]).then(function(results){
                if(results.data !== localStorage.getItem(paths[i] + '_updated')){
                    storageService.updateData(paths[i]).then(function(){
                        $scope[paths[i]] = storageService.getItem(paths[i]);
                    });
                } 
            });
        }
        
        $scope.matchVenue = function (venue){
            return function(event){
                return event.venue_id.match(venue.venue_id);
            };
        };
        
        $scope.matchDay = function (day){
            return function(event){
                return event.event_day.match(day);
            };
        };
    }
]);